package com.fdb.efp.batch.service.impl.yed;

import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.basic.framework.core.exception.BizException;
import com.fdb.basic.framework.core.util.DateUtility;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.efp.batch.service.facade.yed.YedGjjTaskService;
import com.fdb.efp.cus.service.facade.AcctInfoService;
import com.fdb.efp.cus.service.facade.GjjReturnInfoTempService;
import com.fdb.efp.cus.service.vo.AcctInfoVO;
import com.fdb.efp.cus.service.vo.GjjReturnInfoTempVO;
import com.fdb.efp.loan.service.facade.AccLoanService;
import com.fdb.efp.loan.service.facade.LoanRepayDetailService;
import com.fdb.efp.loan.service.facade.LoanRepayPlanService;
import com.fdb.efp.loan.service.vo.AccLoanVO;
import com.fdb.efp.loan.service.vo.LoanRepayDetailVO;
import com.fdb.efp.loan.service.vo.LoanRepayPlanVO;
import com.fdb.efp.nls.common.constant.yed.YedAccLoanUtils;
import com.fdb.efp.nls.service.facade.NlsApplyInfoService;
import com.fdb.efp.nls.service.vo.NlsApplyInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;


/**
 * 需求编号：【2019D0509】（业务提的需求编号）
 * 问题编号：【】（若不是因为修复问题而新增该类，则留空）
 * 开发人员：【wanglh4】
 * 创建日期：【2020/8/12 14:22】
 * 功能描述：
 */
@Service("yedGjjTaskService")
public class YedGjjTaskServiceImpl implements YedGjjTaskService,FrameworkService{

    private static Logger logger = LoggerFactory.getLogger(YedGjjTaskServiceImpl.class);

    @Autowired
    @Qualifier("accLoanService")
    private AccLoanService accLoanService;

    @Autowired
    @Qualifier("nlsApplyInfoService")
    private NlsApplyInfoService nlsApplyInfoService;

    @Autowired
    @Qualifier("accLoanRepayPlanService")
    private LoanRepayPlanService loanRepayPlanService;

    @Autowired
    @Qualifier("loanRepayDetailService")
    private LoanRepayDetailService loanRepayDetailService;

    @Autowired
    @Qualifier("acctInfoService")
    private AcctInfoService acctInfoService;

    @Autowired
    @Qualifier("gjjReturnInfoTempService")
    private GjjReturnInfoTempService gjjReturnInfoTempService;




    @Override
    public boolean doTask(String gjjSubDate) {
        gjjReturnInfoTempService.deleteByPk();
        //1. 公基金列表查询
        try {
            List<AcctInfoVO> list =  acctInfoService.queryGJJList();
            String batchDate = TimeUtil.addDay(gjjSubDate, 1);
            for (AcctInfoVO item : list){
                //2. 借据信息查询
                AccLoanVO accLoanVO = new AccLoanVO();
                accLoanVO.setCertCode(item.getCertCode());
                accLoanVO.setCertType(item.getCertType());
                accLoanVO.setPrdCode("11110004");
                List<AccLoanVO> accLoanVOS = accLoanService.queryByCertandPrd(accLoanVO);
                if (accLoanVOS.size()<1){
                    logger.info("根据证件号码"+item.getCertCode()+"查询借据信息为空，请核查！");
                    continue;
                }
                for (AccLoanVO loanVO : accLoanVOS){
                    // 3.用信信息查询
                    NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO();
                    nlsApplyInfoVO.setApplySeq(loanVO.getApplySeq());
                    NlsApplyInfoVO queryCopy = nlsApplyInfoService.queryCopy(nlsApplyInfoVO);
                    if (Objects.isNull(queryCopy)){
                        logger.debug("根据用信号:"+nlsApplyInfoVO.getApplySeq()+"借据号:"+loanVO.getBillNo()+"查询数据为空");
                        continue;
                    }
                    //4. 还款计划查询
                    LoanRepayPlanVO loanRepayPlanVO = new LoanRepayPlanVO();
                    loanRepayPlanVO.setRefNbr(loanVO.getBillNo());
                    //4.1 累计逾期还款计划查询
                    List<LoanRepayPlanVO> overdueVOS = loanRepayPlanService.queryRepayPlanByRefNbrAndIsOverDue(loanRepayPlanVO);
                    if (Objects.isNull(overdueVOS) || overdueVOS.size()==0){
                        logger.debug("根据借据号"+loanVO.getBillNo()+"查询逾期的还款计划为空！");
                        overdueVOS = new ArrayList<>();
                    }
                    //4.2 正常还款计划查询
                    loanRepayPlanVO.setStatus("N");
                    List<LoanRepayPlanVO> nomalVOS = loanRepayPlanService.getLoanRepayPlanByRefNbrAndStatus(loanRepayPlanVO);
                    if (Objects.isNull(nomalVOS) || nomalVOS.size()==0){
                        logger.debug("根据借据号"+loanVO.getBillNo()+"查询状态为正常的还款计划为空！");
                        nomalVOS = new ArrayList<>();
                    }
                    //4.3 当前逾期还款计划查询
                    loanRepayPlanVO.setStatus("O");
                    List<LoanRepayPlanVO> delayVOS = loanRepayPlanService.getLoanRepayPlanByRefNbrAndStatus(loanRepayPlanVO);

                    //5. 还款明细查询
                    LoanRepayDetailVO loanRepayDetailVO = new LoanRepayDetailVO();
                    loanRepayDetailVO.setLoanNo(loanVO.getBillNo()); // 借据号
                    //5.1 还款成功 的 还款明细数据
                    List<LoanRepayDetailVO> allDetailVOS = loanRepayDetailService.queryDetailBySetlApplyDt(loanRepayDetailVO);
                    List<LoanRepayDetailVO> allDetailDelays = loanRepayDetailService.queryDetailBySetlTyo(loanRepayDetailVO);
                    //5.2 还款成功 且还款申请日期 = 昨天
                    loanRepayDetailVO.setSetlApplyDt(gjjSubDate);
                    List<LoanRepayDetailVO> currDetailVOS = loanRepayDetailService.queryDetailBySetlApplyDt(loanRepayDetailVO);
                    if (Objects.isNull(currDetailVOS) || currDetailVOS.size()==0){
                        logger.debug("根据借据号"+loanVO.getBillNo()+"查询还款明细数据为空！");
                        continue;
                    }
                    //6. 插入数据到临时表
                    GjjReturnInfoTempVO gjjReturnInfoTempVO = new GjjReturnInfoTempVO();
                    gjjReturnInfoTempVO.setStdidno(item.getCertCode());//证件号码
                    gjjReturnInfoTempVO.setStdidtype("01");//证件类型
                    gjjReturnInfoTempVO.setStdcusnm(loanVO.getCusName());//客户姓名
                    gjjReturnInfoTempVO.setStdperid(item.getPrvdntAcctNo());//公积金账号
                    gjjReturnInfoTempVO.setStdsxbh(queryCopy.getLmtApplySeq());//授信编号
                    gjjReturnInfoTempVO.setStdnwst(YedAccLoanUtils.acctStsTrans(loanVO.getAccountStatus()));//当前状态
                    gjjReturnInfoTempVO.setStddate(batchDate.replace("-",""));//数据日期
                    gjjReturnInfoTempVO.setStdfkzh(loanVO.getBillNo());//贷款编号
                    gjjReturnInfoTempVO.setStdjqrq(StringUtil.isNullorBank(loanVO.getSettlDate())?"":loanVO.getSettlDate().replace("-",""));//结清日期 非必输
                    gjjReturnInfoTempVO.setStdljyqqs(overdueVOS.size());

                    //累计逾期本金 、利息
                    repayPlanDelay(delayVOS,gjjReturnInfoTempVO);
                    // 正常还款计划数据封装
                    repayPlanNormal(nomalVOS,gjjReturnInfoTempVO);
                    // 还款明细数据封装
                    repayDetailAll(allDetailVOS,allDetailDelays,gjjReturnInfoTempVO,gjjSubDate);
                    List<GjjReturnInfoTempVO> gjjReturnInfoTempVOS = listToInsert(currDetailVOS,gjjReturnInfoTempVO);
                    logger.info("证件号："+gjjReturnInfoTempVO.getStdidno()+"借据号："+gjjReturnInfoTempVO.getStdfkzh()+"批量插入数据开始... ...");
                    int num = gjjReturnInfoTempService.batchInsert(gjjReturnInfoTempVOS);
                    if (num != gjjReturnInfoTempVOS.size()){
                        logger.debug("插入数据有误，应当插入数据"+gjjReturnInfoTempVOS.size()+"条，实际插入"+num+"条,请核查！");
                        continue;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void repayPlanDelay(List<LoanRepayPlanVO> loanRepayPlanVOS,GjjReturnInfoTempVO gjjReturnInfoTempVO){
        BigDecimal yqbj = new BigDecimal(0);
        BigDecimal yqlx = new BigDecimal(0);
        for (LoanRepayPlanVO loanRepayPlanVO : loanRepayPlanVOS){
            yqbj=yqbj.add(loanRepayPlanVO.getPrincipal().subtract(loanRepayPlanVO.getPrincipalPaid()));
            yqlx=yqlx.add(loanRepayPlanVO.getInterest().subtract(loanRepayPlanVO.getInterestPaid()));
        }
        gjjReturnInfoTempVO.setStdyqqs(loanRepayPlanVOS.size());//逾期期数
        gjjReturnInfoTempVO.setStdyqbj(yqbj);//逾期本金
        gjjReturnInfoTempVO.setStdyqlx(yqlx);//逾期利息
    }

    private void repayPlanNormal(List<LoanRepayPlanVO> loanRepayPlanVOS,GjjReturnInfoTempVO gjjReturnInfoTempVO){
        gjjReturnInfoTempVO.setStdsyqs(loanRepayPlanVOS.size());
        BigDecimal stdfkamt = BigDecimal.ZERO;
        if (loanRepayPlanVOS.size()>0){
            for (LoanRepayPlanVO loanRepayPlanVO : loanRepayPlanVOS){
                stdfkamt=stdfkamt.add(loanRepayPlanVO.getPrincipal());
            }
        }
        gjjReturnInfoTempVO.setStdfkamt(stdfkamt);
    }

    private void repayDetailAll(List<LoanRepayDetailVO> loanRepayDetailVOS,List<LoanRepayDetailVO> loanRepayDetailDelays,GjjReturnInfoTempVO gjjReturnInfoTempVO,String gjjSubDate) throws BizException{
        try {
            BigDecimal stdljhkbj = BigDecimal.ZERO;//累计还款本金
            BigDecimal stdljhklx = BigDecimal.ZERO;//累计还款利息
            BigDecimal stdljhkfx = BigDecimal.ZERO;//累计还款罚息
            BigDecimal stdljyqbj = gjjReturnInfoTempVO.getStdyqbj();//累计逾期本金
            BigDecimal stdljyqlx = gjjReturnInfoTempVO.getStdyqlx();//累计逾期利息
            if (Objects.nonNull(loanRepayDetailVOS) && loanRepayDetailVOS.size()>0){
                for(LoanRepayDetailVO loanRepayDetailVO : loanRepayDetailVOS){
                    if (DateUtility.compareToDate(loanRepayDetailVO.getSetlApplyDt(),gjjSubDate)<1){
                        stdljhkbj=stdljhkbj.add(loanRepayDetailVO.getSetlOdPrcpAmt());
                        stdljhklx=stdljhklx.add(loanRepayDetailVO.getSetlOdNormInt());
                        stdljhkfx=stdljhkfx.add(loanRepayDetailVO.getSetlOdIntAmt());
                    }
                }
            }
            if (Objects.nonNull(loanRepayDetailDelays) && loanRepayDetailDelays.size()>0){
                for(LoanRepayDetailVO item : loanRepayDetailDelays){
                    stdljyqbj=stdljyqbj.add(item.getSetlOdPrcpAmt());
                    stdljyqlx=stdljyqlx.add(item.getSetlOdNormInt());
                }
            }
            gjjReturnInfoTempVO.setStdljhkbj(stdljhkbj);
            gjjReturnInfoTempVO.setStdljhklx(stdljhklx);
            gjjReturnInfoTempVO.setStdljhkfx(stdljhkfx);
            gjjReturnInfoTempVO.setStdljyqbj(stdljyqbj);
            gjjReturnInfoTempVO.setStdljyqlx(stdljyqlx);
        } catch (BizException e) {
            e.printStackTrace();
        }
    }

    private List<GjjReturnInfoTempVO> listToInsert(List<LoanRepayDetailVO> loanRepayDetailVOS,GjjReturnInfoTempVO gjjReturnInfoTempVO){
        List<GjjReturnInfoTempVO> list = new ArrayList<>();
        for (LoanRepayDetailVO item : loanRepayDetailVOS){
            GjjReturnInfoTempVO tempVO = new GjjReturnInfoTempVO();
            beanCopy(gjjReturnInfoTempVO,tempVO);
            tempVO.setStdhkqs(Integer.parseInt(item.getRepayTerm()));//还款期数
            tempVO.setStdtranum(item.getSetlSeq());//银行系统交易流水号
            tempVO.setStdywlx(YedAccLoanUtils.setlTypTrans(item.getSetlTyp()));//交易类型
            tempVO.setStdhkbj(item.getSetlOdPrcpAmt());//本期还款本金
            tempVO.setStdhklx(Objects.isNull(item.getSetlOdNormInt())?BigDecimal.ZERO:item.getSetlOdNormInt());//本期还款利息  为空
            tempVO.setStdhkfx(item.getSetlOdIntAmt());//本期还款罚息
            list.add(tempVO);
        }
        return list;
    }
}
